#pragma once
#include <iostream>
#include <sys/select.h>
#include "Log.hpp"
#include "socket.hpp"

using namespace socket_ns;
static const int N = sizeof(fd_set) * 8;
static const int defaultfd = -1;
class SelectServer
{
public:
    SelectServer(int port)
        : _port(port), _listensocket(std::make_shared<TcpSocket>())
    {
        InetAddr local(port);
        _listensocket->BuildServerSocket(local);
        for (int i = 0; i < N; i++)
        {
            _RfdsArray[i] = defaultfd;
        }
        _RfdsArray[0] = _listensocket->SockFd();
    }
    // listensockfd已经就绪
    void AcceptClient()
    {
        //Log(DEBUG, "enter accpclient");
        InetAddr client;
        // 不会阻塞
        int sockfd = _listensocket->AcceptSocket(&client);
        if (sockfd < 0)
        {
            Log(ERROR, "accept error!");
            return;
        }
        // 连接已满
        else if (sockfd == N)
        {
            Log(ERROR, "当前浏览连接过多,连接sockfd:[%d], ip&&port: [%s:%d]已被强制关闭！", sockfd, client.IP().c_str(), client.port());
            close(sockfd);
        }
        // 正常添加
        else
        {
            for (int i = 1; i < N; i++)
            {
                if (_RfdsArray[i] == defaultfd)
                {
                    Log(DEBUG, "get a new link! sockfd:[%d], ip&&port: [%s:%d]", sockfd, client.IP().c_str(), client.port());
                    _RfdsArray[i] = sockfd;
                    break;
                }
            }
        }
    }
    // readfd就绪
    void ServiceEcho(int pos)
    {

        char recvbuffer[1024];
        int n = recv(_RfdsArray[pos], recvbuffer, sizeof(recvbuffer) - 1, 0);
        //std::cout << "recv end" << std::endl;
        if (n > 0)
        {
            recvbuffer[n] = 0;
            std::cout<<recvbuffer<<std::endl;
            std::string echostring = "Echo Server#";
            echostring += recvbuffer;
            send(_RfdsArray[pos], echostring.c_str(), echostring.size(), 0);
        }
        else if (n == 0)
        {
            Log(ERROR, "%d connect alrady close!", _RfdsArray[pos]);
            close(_RfdsArray[pos]);
            _RfdsArray[pos] = defaultfd;
        }
        else
        {
            Log(ERROR, "%d recv error!", _RfdsArray[pos]);
            close(_RfdsArray[pos]);
            _RfdsArray[pos] = defaultfd;
        }
    }
    void HanderSelect(fd_set &rfds)
    {
        // 分为accept条件就绪与recvfd就绪
        for (int i = 0; i < N; i++)
        {
            if (_RfdsArray[i] == defaultfd)
            {
                continue;
            }
            else if (FD_ISSET(_RfdsArray[i], &rfds))
            {
                if (_RfdsArray[i] == _listensocket->SockFd())
                {
                    AcceptClient();
                }
                else
                {
                    // std::cout << "serviceecho" << std::endl;
                    ServiceEcho(i);
                }
            }
        }
    }

    void start()
    {
        // InetAddr client;
        // int sockfd=_listensocket->AcceptSocket(&client);
        // //通信
        // 创建select文件描述符集合
        while (true)
        {
            sleep(1);
            fd_set rfds;
            // 对该集合进行全部清空
            FD_ZERO(&rfds);
            // 将fd设置进入该集合
            int maxfd = defaultfd;
            for (int i = 0; i < N; i++)
            {
                if (_RfdsArray[i] == defaultfd)
                {
                    continue;
                }
                FD_SET(_RfdsArray[i], &rfds);
                if (maxfd < _RfdsArray[i])
                {
                    maxfd = _RfdsArray[i];
                }
            }
            // 等待就绪条件
            timeval timeout{5, 0};
            // 没有fd条件就绪时五秒返回一次，不对write与异常fd进行设置

            // 返回>0，已就绪个数；==0，达到timeout返回；<0,出错
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);

            switch (n)
            {
            case 0:
                // Log(DEBUG, "select 为0...");
                break;
            case -1:
                Log(DEBUG, "select fail...");
                break;
            default: // 必然有就绪的fd
                // Log(DEBUG, "enter hander");
                HanderSelect(rfds);
                break;
            }
        }
    }

    ~SelectServer()
    {
    }

private:
    int _port;
    socket_ptr _listensocket;
    int _RfdsArray[N]; // 辅助数组，用于rfds的建立
};